package com.one.common.utils.map;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.one.common.utils.Logger;
import com.one.common.utils.MyToast;
import com.one.common.utils.Toaster;

import java.net.URISyntaxException;
import java.util.List;

/**
 * creator: zhulunjun
 * time:    2018/8/9
 * describe: 调导航app
 */
public class MapUtils {

    /**
     * 弹窗选择地图导航
     */
    public static void selectMap(final Context context, final LatLng startPoint, final String startName,
                                 final LatLng endPoint, final String endName) {

        AlertDialog alertDialog = new AlertDialog
                .Builder(context)
                .setItems(new String[]{"腾讯地图", "高德地图", "百度地图"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(startPoint == null || endPoint == null){
                            Toaster.showLongToast("地址信息错误",MyToast.FAIL);
                            return;
                        }
                        switch (which) {
                            case 0:
                                startTencentNavi(context, startPoint, startName, endPoint, endName);
                                break;
                            case 1:
                                startGaoDeNavi(context, endPoint, endName);
                                break;
                            case 2:
                                startBaiduMapNavi(context, endPoint, endName);
                                break;
                            default:
                                break;
                        }
                    }
                }).create();
        alertDialog.show();
    }

    /**
     * 调起百度APP BD-09
     */
    public static void startBaiduMapNavi(final Context context, LatLng endPoint, String endName) {
        try {

            if (!isInstalled(context, "com.baidu.BaiduMap")) {
                Toaster.showLongToast("请先下载安装百度地图客户端", MyToast.FAIL);
                return;
            }
            endPoint = toBD09(endPoint);
//            String startLag = startPoint.latitude + "," + startPoint.longitude;
            String endLag = endPoint.latitude + "," + endPoint.longitude;


            //   Intent intent = Intent.getIntent("intent://map/direction?origin=latlng:" + startLag + "|name:" + startName + "&destination=latlng:" + endLag + "|name:" + endName + "&mode=transit&src=某某公司#Intent;" + "scheme=bdapp;package=com.baidu.BaiduMap;end");
            //起点  此处不传值默认选择当前位置
            Intent intent = Intent.getIntent("intent://map/direction?destination=latlng:" + endLag + "|name:" + endName + "&mode=driving&src=某某公司#Intent;" + "scheme=bdapp;package=com.baidu.BaiduMap;end");


            //            URL接口：baidumap://map/direction
            //            destination : 终点名称或经纬度
            //            经纬度和名称:
            //            latlng:39.9761,116.3282|name:中关村 (注意：坐标先纬度，后经度)
            //            mode : 导航模式 //driving 驾车
            context.startActivity(intent);

        } catch (URISyntaxException e) {
            e.printStackTrace();
            Logger.e("地址解析错误");
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toaster.showLongToast("您尚未安装百度地图APP");
        }
    }


    /**
     * 高德地圖 GCJ-02
     */
    public static void startGaoDeNavi(final Context context, LatLng endPoint, String endName) {
        if (!isInstalled(context, "com.autonavi.minimap")) {
            Toaster.showLongToast("请先下载安装高德地图客户端", MyToast.FAIL);
            return;
        }
//        endPoint = fromBD09(endPoint);//坐标转换

        StringBuffer stringBuffer = new StringBuffer("androidamap://route?sourceApplication=").append("amap");

        stringBuffer.append("&dlat=").append(endPoint.latitude) //终点纬度
                .append("&dlon=").append(endPoint.longitude) //终点经度
                .append("&dname=").append(endName) //终点地址
                .append("&dev=").append(0)  //起终点是否偏移(0:lat 和 lon 是已经加密后的,不需要国测加密; 1:需要国测加密)
                .append("&t=").append(0);  //t = 0（驾车）= 1（公交）= 2（步行）= 3（骑行）= 4（火车）= 5（长途客车）

        Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse(stringBuffer.toString()));
        intent.setPackage("com.autonavi.minimap");
        context.startActivity(intent);
    }


    /**
     * 腾讯地图跳转URI  GCJ-02
     */
    public static void startTencentNavi(Context context, LatLng startPoint, String startName, LatLng endPoint, String endName) {
        if (!isInstalled(context, "com.tencent.map")) {
            Toaster.showLongToast("请先下载安装腾讯地图客户端", MyToast.FAIL);
            return;
        }
//        startPoint = fromBD09(startPoint);//坐标转换
//        endPoint = fromBD09(endPoint);//坐标转换
        StringBuffer stringBuffer = new StringBuffer("qqmap://map/routeplan?type=drive&from=")
                .append(startName)
                .append("&fromcoord=").append(startPoint.latitude).append(",").append(startPoint.longitude)
                .append("&to=").append(endName)
                .append("&tocoord=").append(endPoint.latitude).append(",").append(endPoint.longitude)
                .append("&policy=2")//0：较快捷1：无高速 2：距离
                .append("&referer=trydriver");
        Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse(stringBuffer.toString()));
        context.startActivity(intent);
    }


    /**
     * BD-09 坐标转换成 GCJ-02 坐标
     */
    public static LatLng fromBD09(LatLng bd) {
        double x = bd.longitude - 0.0065, y = bd.latitude - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);

        double[] ret = new double[2];
        ret[1] = z * Math.cos(theta);
        ret[0] = z * Math.sin(theta);
        return new LatLng(ret[0], ret[1]);
    }

    /**
     * GCJ-02 坐标转换成 BD-09 坐标
     */
    private static final double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

    public static LatLng toBD09(LatLng gg) {
        double x = gg.longitude, y = gg.latitude;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double[] ret = new double[2];
        ret[1] = z * Math.cos(theta) + 0.0065;
        ret[0] = z * Math.sin(theta) + 0.006;
        return new LatLng(ret[0], ret[1]);
    }


    public static boolean isInstalled(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();//获取packagemanager
        final List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);//获取所有已安装程序的包信息
        if (pinfo != null) {
            for (PackageInfo info : pinfo) {
                if (info.packageName.equals(packageName)) {
                    return true;
                }
                //pName.add(pn);
            }
        }
        return false;
    }

}
